#define  _CRT_SECURE_NO_WARNINGS
#include "Queue.h"
#include "Tree.h"

Qnode* BuynewNode(QDatatype x)
{
	Qnode* node = (Qnode*)malloc(sizeof(Qnode));
	assert(node);
	node->next = NULL;
	node->data = x;
	return node;
}

void QueueInit(Queue* phead)
{
	assert(phead);
	
	phead->head = phead->tail = NULL;
	phead->size = 0;
}

void QueuePush(Queue* phead, QDatatype x)
{
	assert(phead);
	Qnode* newnode = BuynewNode(x);
	if (phead->tail == NULL)
	{
		phead->tail = phead->head = newnode;
	}
	else
	{
		phead->tail->next = newnode;
		phead->tail = phead->tail->next;
	}
	phead->size++;
}

bool QEmpty(Queue* phead)
{
	assert(phead);
	
	return phead->head == NULL;
}

void QueuePop(Queue* phead)
{
	assert(phead);
	assert(!QEmpty(phead));
	if (phead->head == phead->tail)
	{
		free(phead->head);
		phead->tail = phead->head = NULL;
	}
	else
	{
		Qnode* tmp = phead->head->next;
		free(phead->head);
		phead->head = tmp;
	}
	phead->size--;
}

QDatatype QueueBack(Queue* phead)
{
	assert(phead);
	assert(!QEmpty(phead));

	return phead->tail->data;
}

QDatatype QueueFront(Queue* phead)
{
	assert(phead);
	assert(!QEmpty(phead));
	return phead->head->data;
}

int QueueSize(Queue* phead)
{
	assert(phead);
	return phead->size;
}

void QueueDestroy(Queue* phead)
{
	assert(phead);
	//assert(!QEmpty(phead));
	Qnode* pcur = phead->head;
	while (pcur)
	{
		Qnode* tmp = pcur->next;
		free(pcur);
		pcur = tmp;
	}
	phead->head = phead->tail = NULL;
	phead->size;
}